import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:hongsheng/model/SPClassChartDoughnutData.dart';
import 'package:hongsheng/model/SPClassExpertInfo.dart';
import 'package:hongsheng/model/SPClassSchemeListEntity.dart';
import 'package:hongsheng/pages/common/SPClassNoDataView.dart';
import 'package:hongsheng/pages/home/SPClassSchemeItemView.dart';
import 'package:hongsheng/utils/SPClassCommonMethods.dart';
import 'package:hongsheng/utils/SPClassImageUtil.dart';
import 'package:hongsheng/utils/SPClassStringUtils.dart';
import 'package:hongsheng/api/SPClassApiManager.dart';
import 'package:hongsheng/api/SPClassHttpCallBack.dart';
import 'package:hongsheng/utils/colors.dart';
import 'package:syncfusion_flutter_charts/charts.dart';

class SPClassExpertLeagueDetail extends StatefulWidget {
  final String ?nickName;
  final String ?expertUid;
  final String ?leagueName;
  final int ?index;
  const SPClassExpertLeagueDetail({Key? key,this.nickName,this.expertUid,this.leagueName,this.index}) : super(key: key);

  @override
  _SPClassExpertLeagueDetailState createState() => _SPClassExpertLeagueDetailState();
}

class _SPClassExpertLeagueDetailState extends State<SPClassExpertLeagueDetail> with TickerProviderStateMixin{
  List leaguesTimeList = ['近7天','近30天','全周期'];
  String selectTime ='近7天';
  SPClassExpertInfo ?data;
  TabController ?_tabController;
  int index =0;
  List<SPClassSchemeListSchemeList> spProSchemeList =[];
  List<SPClassSchemeListSchemeList> spProSchemeHistory=[];


  @override
  void initState() {
    index =widget.index!;
    selectTime = leaguesTimeList[index];
    _tabController= TabController(initialIndex: index,length: leaguesTimeList.length,vsync: this);
    getLeagueDetail();
    getSchemeList();
    // TODO: implement initState
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: new AppBar(
        elevation: 0,
        leading: FlatButton(
          child: Icon(Icons.arrow_back_ios,size: width(20),color: Colors.white,),
          onPressed: (){Navigator.of(context).pop();},
        ),
        centerTitle: true,
        title: Text("${widget.leagueName}",style: TextStyle(fontSize:  sp(16)),),
      ),
      body: Stack(
        children: <Widget>[
          Container(
            color: Color(0xFFF1F1F1),
            width: MediaQuery.of(context).size.width,
            height: MediaQuery.of(context).size.height,
          ),
          Positioned(
            top: 0,
            right: 0,
            left: 0,
            child: Container(
              color: Theme.of(context).primaryColor,
              height: height(60),
            ),
          ),
          Positioned(
            left: 0,
            right: 0,
            top: 0,
            bottom: 0,
            child: SingleChildScrollView(
              child: Column(
                children: <Widget>[
                  Container(
                    width: MediaQuery.of(context).size.width,
                    padding: EdgeInsets.all(width(12)),
                    margin: EdgeInsets.symmetric(horizontal: width(14)),
                    decoration: BoxDecoration(
                      color: Colors.white,
                      borderRadius: BorderRadius.circular(8)
                    ),
                    child: Column(
                      children: <Widget>[
                        Row(
                          children: <Widget>[
                            Container(
                              width: 2,
                              height: width(14),
                              color: MyColors.main1,
                            ),
                            SizedBox(width: width(6),),
                            RichText(
                              text: TextSpan(
                                text: '联赛胜率',
                                style: TextStyle(
                                  fontSize: sp(14),
                                  color: MyColors.grey_33,
                                  fontWeight: FontWeight.w600,
                                  height: 1.2
                                ),
                                children: [
                                  TextSpan(
                                    text: '[${SPClassStringUtils.spFunMaxLength(widget.leagueName??'',length: 4)}]',
                                    style: TextStyle(
                                      fontSize: sp(12),
                                      color: MyColors.grey_99
                                    )
                                  )
                                ]
                              ),
                            ),
                            Expanded(
                              child: SizedBox(),
                            ),
                            Row(
                              mainAxisAlignment: MainAxisAlignment.end,
                              children: leaguesTimeList.map((e) {
                                return InkWell(
                                  onTap: (){
                                    selectTime = e;
                                    index = leaguesTimeList.indexOf(e);
                                    _tabController?.animateTo(index);
                                    setState(() {
                                    });
                                  },
                                  child: Container(
                                    width: width(54),
                                    height: width(20),
                                    alignment: Alignment.center,
                                    margin: EdgeInsets.only(left: width(8)),
                                    decoration: BoxDecoration(
                                        color:selectTime==e?MyColors.main1: Color(0xFFF2F2F2),
                                        borderRadius: BorderRadius.circular(4)
                                    ),
                                    child: Text(e,style: TextStyle(fontSize: sp(12),color:selectTime==e?Colors.white:MyColors.grey_99),),
                                  ),
                                );
                              }).toList(),
                            ),
                          ],
                        ),
                        SizedBox(height: width(10),),
                        data==null?Container():Container(
                          height: width(120),
                          child: TabBarView(
                            controller: _tabController,
                            children: <Widget>[
                              chartWidget(data?.spProHit?.spProWeek),
                              chartWidget(data?.spProHit?.spProMonth),
                              chartWidget(data?.spProHit?.spProAll),
                            ],
                          ),
                        )
                      ],
                    ),
                  ),
                  spProSchemeList.length==0?SizedBox():  Container(
                    margin: EdgeInsets.only(left: width(13),right:  width(13),top:width(8) ),
                    decoration: BoxDecoration(
                      color: Colors.white,
                      borderRadius: BorderRadius.circular(width(7)),
                      boxShadow:[
                        BoxShadow(
                          offset: Offset(2,5),
                          color: Color(0x0D000000),
                          blurRadius:width(6,),),
                        BoxShadow(
                          offset: Offset(-5,1),
                          color: Color(0x0D000000),
                          blurRadius:width(6,),
                        )
                      ],
                    ),
                    width: MediaQuery.of(context).size.width,

                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: <Widget>[
                        Container(
                          height: height(35),
                          padding: EdgeInsets.only(left: width(13),right: width(13)),
                          decoration: BoxDecoration(
                              border: Border(bottom: BorderSide(width: 0.4,color: Colors.grey[300]!))
                          ),
                          child: Row(
                            children: <Widget>[
                              Container(
                                width: height(4),
                                height: height(14),
                                decoration: BoxDecoration(
                                    color: Color(0xFFDE3C31),
                                    borderRadius: BorderRadius.circular(100)
                                ),
                              ),
                              SizedBox(width: 4,),
                              Text("最新方案",style: TextStyle(fontWeight: FontWeight.w600,fontSize: width(15)),),

                            ],
                          ),
                        ),
                        ListView.builder(
                            physics: NeverScrollableScrollPhysics(),
                            shrinkWrap: true,
                            padding: EdgeInsets.only(bottom: width(5)),
                            itemCount: spProSchemeList.length,
                            itemBuilder: (c,index){
                              var item=spProSchemeList[index];
                              return SPClassSchemeItemView(item,spProCanClick: false,spProShowLine:spProSchemeList.length>(index+1));
                            })
                      ],
                    ),
                  ),
                  Container(
                    margin: EdgeInsets.only(left: width(13),right:  width(13),top:width(8),bottom:width(8) ),
                    decoration: BoxDecoration(
                      color: Colors.white,
                      borderRadius: BorderRadius.circular(width(7)),
                      boxShadow:[
                        BoxShadow(
                          offset: Offset(2,5),
                          color: Color(0x0D000000),
                          blurRadius:width(6,),),
                        BoxShadow(
                          offset: Offset(-5,1),
                          color: Color(0x0D000000),
                          blurRadius:width(6,),
                        )
                      ],
                    ),
                    width: MediaQuery.of(context).size.width,

                    child:spProSchemeHistory.isEmpty?SizedBox(): Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: <Widget>[
                        Container(
                          height: height(35),
                          padding: EdgeInsets.only(left: width(13),right: width(13)),
                          decoration: BoxDecoration(
                              border: Border(bottom: BorderSide(width: 0.4,color: Colors.grey[300]!))
                          ),
                          child: Row(
                            children: <Widget>[
                              Container(
                                width: height(4),
                                height: height(14),
                                decoration: BoxDecoration(
                                    color: Color(0xFFDE3C31),
                                    borderRadius: BorderRadius.circular(100)
                                ),
                              ),
                              SizedBox(width: 4,),
                              Text("历史推荐",style: TextStyle(fontWeight: FontWeight.w600,fontSize: width(15)),),

                            ],
                          ),
                        ),
                        ListView.builder(
                            physics: NeverScrollableScrollPhysics(),
                            shrinkWrap: true,
                            padding: EdgeInsets.only(bottom: width(5)),
                            itemCount: spProSchemeHistory.length,
                            itemBuilder: (c,index){
                              var item=spProSchemeHistory[index];
                              return Stack(
                                children: <Widget>[
                                  SPClassSchemeItemView(item,spProShowRate: false,spProShowLine:spProSchemeHistory.length>(index+1),),
                                  Positioned(
                                    top: 10,
                                    right:  width(13) ,
                                    child: Image.asset(
                                      (item.spProIsWin=="1")? SPClassImageUtil.spFunGetImagePath("ic_result_red"):
                                      (item.spProIsWin=="0")? SPClassImageUtil.spFunGetImagePath("ic_result_hei"):
                                      (item.spProIsWin=="2")? SPClassImageUtil.spFunGetImagePath("ic_result_zou"):"",
                                      width: width(40),
                                    ),
                                  ),
                                ],
                              );
                            })
                      ],
                    ),
                  ),

                ],
              ),
            ),
          )
        ],
      ),
    );
  }

  Widget  chartWidget(SPClassHitDetail ?data){
    return data?.spProCount==0?SPClassNoDataView(height: width(120),iconSize: Size(width(80),width(80)),):Row(
      mainAxisAlignment: MainAxisAlignment.spaceAround,
      children: <Widget>[
        Stack(
          alignment: Alignment.center,
          children: <Widget>[
            Container(
              height: width(120),
              width: width(120),
              child:SfCircularChart(
                margin: EdgeInsets.zero,
                title: ChartTitle(text: '' ),
                legend: Legend(isVisible: false),
                series: [
                  DoughnutSeries<SPClassChartDoughnutData, String>(
                    explode: false,
                    explodeIndex: 0,
                    radius: width(50).toString(),
                    innerRadius: width(43).toString(),
                    dataSource: [
                      SPClassChartDoughnutData(getPercent(data!,'红')/100,color: Color(0xFFDE3C31)),
                      SPClassChartDoughnutData(getPercent(data,'走')/100,color: Colors.green),
                      SPClassChartDoughnutData(getPercent(data,'黑')/100,color: MyColors.grey_66),
                    ],
                    xValueMapper: (SPClassChartDoughnutData data, _) => "",
                    yValueMapper: (SPClassChartDoughnutData data, _) => data.percenter,
                    pointColorMapper:(SPClassChartDoughnutData data, _) => data.color,
                    startAngle: 90,
                    endAngle: 90,
                  ),

                ],
              ),
            ),
            RichText(
              text: TextSpan(
                  text: '${data.spProCount}场',
                  style: TextStyle(
                    fontSize: sp(14),
                    color: MyColors.main1,
                    fontWeight: FontWeight.w600,
                  ),
                  children: [
                    TextSpan(
                        text: '\n 总',
                        style: TextStyle(
                            fontSize: sp(14),
                            color: MyColors.grey_99
                        )
                    )
                  ]
              ),
            ),
          ],
        ),
        Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            SizedBox(height: width(25),),
            getPercentWidget('红',data),
            getPercentWidget('走',data),
            getPercentWidget('黑',data),
          ],
        ),
      ],
    );
  }

  Widget getPercentWidget(String type,SPClassHitDetail data){
    return Container(
      margin: EdgeInsets.symmetric(vertical: width(2)),
      child:Row(
        children: <Widget>[
          Stack(
            alignment: Alignment.center,
            children: <Widget>[
              Image.asset(SPClassImageUtil.spFunGetImagePath('ic_pingxing'),width: width(36),color:type=='红'?MyColors.main1:type=='走'? Colors.green:MyColors.grey_66,),
              Text(type,style: TextStyle(fontSize: sp(12),color: Colors.white),)
            ],
          ),
          Text('${getPercent(data,type)}%',style: TextStyle(fontSize: sp(14),color: MyColors.main1),)
        ],
      ) ,
    );
  }

  getPercent(SPClassHitDetail data,String type){
    if(data==null||data.spProCount==0){
      return 0;
    }
    if(type=='红'&&data.spProRed!=0){
      return int.parse(((data.spProRed!/data.spProCount!)*100).toStringAsFixed(0));
    }
    if(type=='走'&&data.spProGo!=0){
      return int.parse(((data.spProGo!/data.spProCount!)*100).toStringAsFixed(0));
    }
    if(type=='黑'&&data.spProBlack!=0){
      return int.parse(((data.spProBlack!/data.spProCount!)*100).toStringAsFixed(0));
    }

    return 0;
  }

  getLeagueDetail(){
    SPClassApiManager.spFunGetInstance().spFunGetLeagueDetail(
      queryParameters: {
        'league_name':widget.leagueName,
        'expert_uid':widget.expertUid,
      },
      spProCallBack: SPClassHttpCallBack(
          spProOnSuccess: (v){
            data =v;
            setState(() {

            });
          },
        spProOnProgress: (v){
        },
        onError: (e){},
      )
    );
  }

  getSchemeList(){
    SPClassApiManager.spFunGetInstance().spFunSchemeList(queryParameters: {"expert_uid":widget.expertUid,"fetch_type":"expert","league_name":widget.leagueName},spProCallBack: SPClassHttpCallBack<SPClassSchemeListEntity>(
        spProOnSuccess: (list){
          list.spProSchemeList?.forEach((itemx){
            if(itemx.spProIsOver=="1"){
              spProSchemeHistory.add(itemx);
            }else{
              spProSchemeList.add(itemx);

            }
          });
          setState(() {

          });
        },
        onError: (value){
        },spProOnProgress: (v){

    }
    ));
  }
}
